package com.example.springbootdemo.beandefinationregister;

import org.springframework.beans.factory.FactoryBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MapperFactoryBean<T> implements FactoryBean<T> {

    private Class<T> targetClass;

    public MapperFactoryBean(Class<T> targetClass) {
        this.targetClass = targetClass;
    }

    @Override
    public T getObject() throws Exception {
        return (T) Proxy.newProxyInstance(targetClass.getClassLoader(), new Class[]{targetClass}, new MapperInvocationHandler());
    }

    @Override
    public Class<?> getObjectType() {
        return targetClass;
    }

    class MapperInvocationHandler implements InvocationHandler {

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if(method.getDeclaringClass().equals(Object.class)) {
                return method.invoke(this, args);
            }
            System.out.println("执行代理方法");
            return null;
        }
    }
}
